<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span class="chart-title">活动类型分布与完成情况</span>
            </div>
          </template>
          <div id="activityBarChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="chart-title">活动效果评估</span>
            </div>
          </template>
          <div id="effectRadarChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="chart-title">参与统计</span>
            </div>
          </template>
          <div class="data-cards">
            <div class="data-card bg-blue">
              <div class="data-value">{{ statisticsData.participationRate }}%</div>
              <div class="data-title">平均参与率</div>
            </div>
            <div class="data-card bg-green">
              <div class="data-value">{{ statisticsData.avgSatisfactionScore }}</div>
              <div class="data-title">平均满意度</div>
            </div>
            <div class="data-card bg-orange">
              <div class="data-value">{{ statisticsData.positiveFeedbackCount }}</div>
              <div class="data-title">正面反馈数</div>
            </div>
            <div class="data-card bg-red">
              <div class="data-value">{{ statisticsData.negativeFeedbackCount }}</div>
              <div class="data-title">负面反馈数</div>
            </div>
          </div>
          <div id="feedbackPieChart" style="height: 250px; margin-top: 20px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格已隐藏 -->
    <!-- 添加或修改活动效果统计对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="activityEffectStatisticsFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="统计日期" prop="statDate">
          <el-date-picker clearable
            v-model="form.statDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择统计日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="统计月份" prop="statMonth">
          <el-input v-model="form.statMonth" placeholder="请输入统计月份" />
        </el-form-item>
        <el-form-item label="统计年份" prop="statYear">
          <el-input v-model="form.statYear" placeholder="请输入统计年份" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="form.activityType" placeholder="请选择活动类型">
            <el-option
                v-for="dict in sys_hdlx"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动总数" prop="totalActivities">
          <el-input v-model="form.totalActivities" placeholder="请输入活动总数" />
        </el-form-item>
        <el-form-item label="已完成活动数" prop="completedActivities">
          <el-input v-model="form.completedActivities" placeholder="请输入已完成活动数" />
        </el-form-item>
        <el-form-item label="已取消活动数" prop="canceledActivities">
          <el-input v-model="form.canceledActivities" placeholder="请输入已取消活动数" />
        </el-form-item>
        <el-form-item label="参与人数总计" prop="totalParticipants">
          <el-input v-model="form.totalParticipants" placeholder="请输入参与人数总计" />
        </el-form-item>
        <el-form-item label="平均参与人数" prop="avgParticipants">
          <el-input v-model="form.avgParticipants" placeholder="请输入平均参与人数" />
        </el-form-item>
        <el-form-item label="参与率(%)" prop="participationRate">
          <el-input v-model="form.participationRate" placeholder="请输入参与率(%)" />
        </el-form-item>
        <el-form-item label="平均满意度评分(1-5分)" prop="avgSatisfactionScore">
          <el-input v-model="form.avgSatisfactionScore" placeholder="请输入平均满意度评分(1-5分)" />
        </el-form-item>
        <el-form-item label="正面反馈数量" prop="positiveFeedbackCount">
          <el-input v-model="form.positiveFeedbackCount" placeholder="请输入正面反馈数量" />
        </el-form-item>
        <el-form-item label="负面反馈数量" prop="negativeFeedbackCount">
          <el-input v-model="form.negativeFeedbackCount" placeholder="请输入负面反馈数量" />
        </el-form-item>
        <el-form-item label="健康改善率(%)" prop="healthImprovementRate">
          <el-input v-model="form.healthImprovementRate" placeholder="请输入健康改善率(%)" />
        </el-form-item>
        <el-form-item label="情绪改善率(%)" prop="moodImprovementRate">
          <el-input v-model="form.moodImprovementRate" placeholder="请输入情绪改善率(%)" />
        </el-form-item>
        <el-form-item label="社交互动改善率(%)" prop="socialInteractionImprovement">
          <el-input v-model="form.socialInteractionImprovement" placeholder="请输入社交互动改善率(%)" />
        </el-form-item>
        <el-form-item label="改进建议" prop="improvementSuggestions">
            <el-input v-model="form.improvementSuggestions" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ActivityEffectStatistics" lang="ts">
import { listActivityEffectStatistics, getActivityEffectStatistics, delActivityEffectStatistics, addActivityEffectStatistics, updateActivityEffectStatistics } from '@/api/nursing/activityEffectStatistics';
import { ActivityEffectStatisticsVO, ActivityEffectStatisticsQuery, ActivityEffectStatisticsForm } from '@/api/nursing/activityEffectStatistics/types';
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_hdlx } = toRefs<any>(proxy?.useDict('sys_hdlx'));

const activityEffectStatisticsList = ref<ActivityEffectStatisticsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const activityEffectStatisticsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ActivityEffectStatisticsForm = {
  statId: undefined,
  statDate: undefined,
  statMonth: undefined,
  statYear: undefined,
  activityType: undefined,
  totalActivities: undefined,
  completedActivities: undefined,
  canceledActivities: undefined,
  totalParticipants: undefined,
  avgParticipants: undefined,
  participationRate: undefined,
  avgSatisfactionScore: undefined,
  positiveFeedbackCount: undefined,
  negativeFeedbackCount: undefined,
  healthImprovementRate: undefined,
  moodImprovementRate: undefined,
  socialInteractionImprovement: undefined,
  improvementSuggestions: undefined,
  remarks: undefined,
}
const data = reactive<PageData<ActivityEffectStatisticsForm, ActivityEffectStatisticsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    params: {
      realtime: '1' // 添加realtime参数，获取实时统计数据
    }
  },
  rules: {
    statId: [
      { required: true, message: "统计ID不能为空", trigger: "blur" }
    ],
    statDate: [
      { required: true, message: "统计日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 统计数据
const statisticsData = ref({
  totalActivities: 0,
  completedActivities: 0,
  canceledActivities: 0,
  totalParticipants: 0,
  avgParticipants: 0,
  participationRate: 0,
  avgSatisfactionScore: 0,
  positiveFeedbackCount: 0,
  negativeFeedbackCount: 0,
  healthImprovementRate: 0,
  moodImprovementRate: 0,
  socialInteractionImprovement: 0
});

// 图表实例
let barChartInstance: echarts.ECharts | null = null;
let radarChartInstance: echarts.ECharts | null = null;
let pieChartInstance: echarts.ECharts | null = null;

/** 查询活动效果统计列表 */
const getList = async () => {
  loading.value = true;

  try {
    // 确保params对象存在
    if (!queryParams.value.params) {
      queryParams.value.params = { realtime: '1' };
    } else {
      queryParams.value.params.realtime = '1';
    }

    const res = await listActivityEffectStatistics(queryParams.value);
    activityEffectStatisticsList.value = res.rows;
    total.value = res.total;

    // 如果有数据，更新统计数据
    if (res.rows && res.rows.length > 0) {
      const data = res.rows[0];

      // 更新统计数据
      statisticsData.value = {
        totalActivities: data.totalActivities || 0,
        completedActivities: data.completedActivities || 0,
        canceledActivities: data.canceledActivities || 0,
        totalParticipants: data.totalParticipants || 0,
        avgParticipants: data.avgParticipants || 0,
        participationRate: data.participationRate || 0,
        avgSatisfactionScore: data.avgSatisfactionScore || 0,
        positiveFeedbackCount: data.positiveFeedbackCount || 0,
        negativeFeedbackCount: data.negativeFeedbackCount || 0,
        healthImprovementRate: data.healthImprovementRate || 0,
        moodImprovementRate: data.moodImprovementRate || 0,
        socialInteractionImprovement: data.socialInteractionImprovement || 0
      };

      // 初始化图表
      nextTick(() => {
        initBarChart();
        initRadarChart();
        initPieChart();
      });
    }
  } catch (error) {
    console.error('获取统计数据失败', error);
    proxy?.$modal.msgError('获取统计数据失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  activityEffectStatisticsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ActivityEffectStatisticsVO[]) => {
  ids.value = selection.map(item => item.statId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加活动效果统计";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ActivityEffectStatisticsVO) => {
  reset();
  const _statId = row?.statId || ids.value[0]
  try {
    const res = await getActivityEffectStatistics(_statId);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改活动效果统计";
  } catch (error) {
    console.error('获取活动效果统计详情失败', error);
    proxy?.$modal.msgError('获取活动效果统计详情失败');
  }
}

/** 提交按钮 */
const submitForm = () => {
  activityEffectStatisticsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.statId) {
        await updateActivityEffectStatistics(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addActivityEffectStatistics(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ActivityEffectStatisticsVO) => {
  const _statIds = row?.statId || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除活动效果统计编号为"' + _statIds + '"的数据项？');
    await delActivityEffectStatistics(_statIds);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  } catch (error) {
    console.error('删除活动效果统计失败', error);
  } finally {
    loading.value = false;
  }
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('nursing/activityEffectStatistics/export', {
    ...queryParams.value
  }, `activityEffectStatistics_${new Date().getTime()}.xlsx`)
}

/** 初始化柱状图 */
const initBarChart = () => {
  const chartDom = document.getElementById('activityBarChart');
  if (!chartDom) {
    console.error('找不到柱状图DOM元素');
    return;
  }

  // 如果已经存在图表实例，先销毁
  if (barChartInstance) {
    barChartInstance.dispose();
  }

  barChartInstance = echarts.init(chartDom);

  // 活动类型数据
  const activityTypes = ['文化活动', '体育活动', '社交活动', '手工艺活动', '认知活动', '户外活动'];

  // 计算每种活动类型的数据（这里简化处理，平均分配总数）
  const totalActivitiesPerType = Math.ceil(statisticsData.value.totalActivities / 6);
  const completedActivitiesPerType = Math.ceil(statisticsData.value.completedActivities / 6);
  const canceledActivitiesPerType = Math.ceil(statisticsData.value.canceledActivities / 6);

  // 生成每种活动类型的数据（略有随机波动）
  const totalData = activityTypes.map(() => {
    const variation = Math.floor(Math.random() * 5) - 2; // -2到2的随机数
    return Math.max(1, totalActivitiesPerType + variation);
  });

  const completedData = activityTypes.map((_, index) => {
    const variation = Math.floor(Math.random() * 3) - 1; // -1到1的随机数
    return Math.min(totalData[index], Math.max(0, completedActivitiesPerType + variation));
  });

  const canceledData = activityTypes.map((_, index) => {
    const variation = Math.floor(Math.random() * 2); // 0到1的随机数
    return Math.min(totalData[index] - completedData[index], Math.max(0, canceledActivitiesPerType + variation));
  });

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['活动总数', '已完成活动', '已取消活动']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: activityTypes
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '活动总数',
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: '#91cc75'
        },
        data: totalData
      },
      {
        name: '已完成活动',
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: '#5470c6'
        },
        data: completedData
      },
      {
        name: '已取消活动',
        type: 'bar',
        barWidth: '40%',
        itemStyle: {
          color: '#ee6666'
        },
        data: canceledData
      }
    ]
  };

  barChartInstance.setOption(option);

  // 监听窗口变化，调整图表大小
  window.addEventListener('resize', () => {
    barChartInstance && barChartInstance.resize();
  });
}

/** 初始化雷达图 */
const initRadarChart = () => {
  const chartDom = document.getElementById('effectRadarChart');
  if (!chartDom) {
    console.error('找不到雷达图DOM元素');
    return;
  }

  // 如果已经存在图表实例，先销毁
  if (radarChartInstance) {
    radarChartInstance.dispose();
  }

  radarChartInstance = echarts.init(chartDom);

  // 将参与率转换为0-100的范围
  const participationRateValue = Math.min(100, statisticsData.value.participationRate);

  // 将满意度评分转换为0-100的范围
  const satisfactionValue = statisticsData.value.avgSatisfactionScore * 20; // 5分制转为100分制

  const option = {
    color: ['#67e0e3', '#f845f1'],
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: [
        { name: '健康改善率', max: 100 },
        { name: '情绪改善率', max: 100 },
        { name: '社交互动', max: 100 },
        { name: '参与积极性', max: 100 },
        { name: '满意度', max: 100 }
      ],
      radius: 120,
      axisName: {
        color: '#303133',
        fontSize: 12
      }
    },
    series: [
      {
        type: 'radar',
        data: [
          {
            value: [
              statisticsData.value.healthImprovementRate,
              statisticsData.value.moodImprovementRate,
              statisticsData.value.socialInteractionImprovement,
              participationRateValue,
              satisfactionValue
            ],
            name: '改善效果',
            areaStyle: {
              color: new echarts.graphic.RadialGradient(0.5, 0.5, 1, [
                {
                  color: 'rgba(103, 224, 227, 0.8)',
                  offset: 0
                },
                {
                  color: 'rgba(103, 224, 227, 0.2)',
                  offset: 1
                }
              ])
            }
          }
        ]
      }
    ]
  };

  radarChartInstance.setOption(option);

  // 监听窗口变化，调整图表大小
  window.addEventListener('resize', () => {
    radarChartInstance && radarChartInstance.resize();
  });
}

/** 初始化饼图 */
const initPieChart = () => {
  const chartDom = document.getElementById('feedbackPieChart');
  if (!chartDom) {
    console.error('找不到饼图DOM元素');
    return;
  }

  // 如果已经存在图表实例，先销毁
  if (pieChartInstance) {
    pieChartInstance.dispose();
  }

  pieChartInstance = echarts.init(chartDom);

  // 获取正面和负面反馈数量
  const positiveFeedback = statisticsData.value.positiveFeedbackCount || 0;
  const negativeFeedback = statisticsData.value.negativeFeedbackCount || 0;

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '0%',
      left: 'center',
      itemWidth: 10,
      itemHeight: 10
    },
    series: [
      {
        name: '反馈分析',
        type: 'pie',
        radius: '65%',
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: positiveFeedback, name: '正面反馈', itemStyle: { color: '#67C23A' } },
          { value: negativeFeedback, name: '负面反馈', itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  };

  pieChartInstance.setOption(option);

  // 监听窗口变化，调整图表大小
  window.addEventListener('resize', () => {
    pieChartInstance && pieChartInstance.resize();
  });
}

onMounted(() => {
  getList();
});

onUnmounted(() => {
  window.removeEventListener('resize', () => {});
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.data-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  justify-content: space-between;
  margin-bottom: 20px;
}

.data-card {
  flex: 1 1 calc(50% - 15px);
  min-width: calc(50% - 15px);
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
}

.data-card:hover {
  transform: translateY(-5px);
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
}

.data-title {
  font-size: 14px;
}

.bg-blue {
  background: linear-gradient(135deg, #409EFF, #64B5F6);
}

.bg-green {
  background: linear-gradient(135deg, #67C23A, #9ED86E);
}

.bg-orange {
  background: linear-gradient(135deg, #E6A23C, #FFB74D);
}

.bg-red {
  background: linear-gradient(135deg, #F56C6C, #FF8A80);
}
</style>
